package com.ysy.tz.core.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.Hashtable;
import java.util.Map;

import com.ysy.tz.core.image.MatrixImage;
import javafx.scene.image.WritableImage;

public class QRCodeUtils {
    public QRCodeUtils() {
    }

    private static int getNewWidth(int width, String contents) {
        Code128Writer code128Writer = new Code128Writer();
        boolean[] code = code128Writer.encode(contents);
        int inputWidth = code.length;
        int outputWidth = Math.max(width, inputWidth);
        int remain = outputWidth % inputWidth;
        return outputWidth - remain;
    }

    public static WritableImage writeBarCodeToImage(String contents, int width, int height) {
        try {
            BitMatrix bitMatrix = (new MultiFormatWriter()).encode(contents, BarcodeFormat.CODE_128, getNewWidth(width, contents), height, (Map)null);
            WritableImage writableImage = (new MatrixImage(bitMatrix)).getImage();
            return (new MatrixImage(bitMatrix)).getImage();
        } catch (Exception var5) {
            var5.printStackTrace();
            return null;
        }
    }

    public static WritableImage writeQRCodeToImage(String str, int width, int height) throws Exception {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Hashtable<EncodeHintType, Object> hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);
        hints.put(EncodeHintType.MARGIN, "0");
        BitMatrix byteMatrix = qrCodeWriter.encode(str, BarcodeFormat.QR_CODE, width, height, hints);
        return (new MatrixImage(byteMatrix)).getImage();
    }
}
